﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Net.Http;
using System.Net.Http.Headers;
using TPLOAWebClient.Resources;
using System.Web.Security;

namespace TPLOAWebClient
{
    public partial class adminmanagementtools : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpClient client = (HttpClient)Session["httpclient"];

            HttpResponseMessage response = null;
            if (Session["username"] != null)
            {
                response = client.GetAsync("api/members/" + Session["username"]).Result;
                var member = response.Content.ReadAsAsync<Member>().Result;
                if (member.UserType.Equals("Student"))
                {
                    Response.Redirect("studentprofile.aspx");
                }
                else if (member.UserType.Equals("Clinic"))
                {
                    Response.Redirect("clinicprofile.aspx");
                }
                else if (member.UserType.Equals("Staff"))
                {
                    Response.Redirect("staffprofile.aspx");
                }
            }

            if (!Page.IsPostBack)
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                response = client.GetAsync("api/Staffs").Result;  // Blocking call!
                {
                    if (response.IsSuccessStatusCode)
                    {
                        // Parse the response body. Blocking!
                        ArrayList array = new ArrayList();
                        var staff = response.Content.ReadAsAsync<IEnumerable<Staff>>().Result;
                        if (staff != null)
                        {
                            foreach (var s in staff)
                            {
                                array.Add(s.StaffID);
                            }
                            staffDdl.DataSource = array;
                            staffDdl.DataBind();
                        }

                    }
                }

                response = client.GetAsync("api/Students").Result;  // Blocking call!
                {
                    if (response.IsSuccessStatusCode)
                    {
                        // Parse the response body. Blocking!
                        ArrayList array = new ArrayList();
                        var student = response.Content.ReadAsAsync<IEnumerable<Student>>().Result;
                        if (student != null)
                        {
                            foreach (var s in student)
                            {
                                array.Add(s.AdminNo);
                            }
                            studentDdl.DataSource = array;
                            studentDdl.DataBind();
                        }

                    }
                }
                
                Panel2.Visible = false;
                Panel3.Visible = false;
                Panel4.Visible = false;
            }
        }

        protected void peopleRbl_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (chooseRbl.SelectedValue == "Create" && peopleRbl.SelectedValue == "Staff")
            {
                Panel1.Visible = true;
                Panel2.Visible = false;
                Panel3.Visible = false;
                Panel4.Visible = false;
            }
            else if (chooseRbl.SelectedValue == "Create" && peopleRbl.SelectedValue == "Student")
            {
                Panel1.Visible = false;
                Panel2.Visible = true;
                Panel3.Visible = false;
                Panel4.Visible = false;
            }
            else if (chooseRbl.SelectedValue == "Update" && peopleRbl.SelectedValue == "Staff")
            {
                Panel1.Visible = false;
                Panel2.Visible = false;
                Panel3.Visible = true;
                Panel4.Visible = false;
            }
            else if (chooseRbl.SelectedValue == "Update" && peopleRbl.SelectedValue == "Student")
            {
                Panel1.Visible = false;
                Panel2.Visible = false;
                Panel3.Visible = false;
                Panel4.Visible = true;
            }
        }

        protected void chooseRbl_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (chooseRbl.SelectedValue == "Create" && peopleRbl.SelectedValue == "Staff")
            {
                Panel1.Visible = true;
                Panel2.Visible = false;
                Panel3.Visible = false;
                Panel4.Visible = false;
            }
            else if (chooseRbl.SelectedValue == "Create" && peopleRbl.SelectedValue == "Student")
            {
                Panel1.Visible = false;
                Panel2.Visible = true;
                Panel3.Visible = false;
                Panel4.Visible = false;
            }
            else if (chooseRbl.SelectedValue == "Update" && peopleRbl.SelectedValue == "Staff")
            {
                Panel1.Visible = false;
                Panel2.Visible = false;
                Panel3.Visible = true;
                Panel4.Visible = false;
            }
            else if (chooseRbl.SelectedValue == "Update" && peopleRbl.SelectedValue == "Student")
            {
                Panel1.Visible = false;
                Panel2.Visible = false;
                Panel3.Visible = false;
                Panel4.Visible = true;
            }
        }

        protected void createstaffBtn_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                HttpClient client = (HttpClient)Session["httpclient"];

                HttpResponseMessage response3 = client.GetAsync("api/Staffs/" + staffidTbx.Text).Result;
                
                bool approvepermission = false;
                if (capprovepermissionRbl.SelectedValue == "Yes")
                {
                    approvepermission = true;
                }
                bool adminright = false;
                if (cadminrightRbl.SelectedValue == "Yes")
                {
                    adminright = true;
                }
                var staff = new Staff()
                {
                    StaffID = cstaffidTbx.Text,
                    Name = cstaffnameTbx.Text,
                    Email = cstaffemailTbx.Text,
                    CourseCode = cstaffcoursecodeRbl.SelectedValue,
                    ApprovePermissions = approvepermission,
                    AdminRights = adminright
                };
                string usertype = "Staff";
                if (adminright == true)
                {
                    usertype = "Admin";
                }
                var User = new Member()
                {
                    Username = cstaffidTbx.Text,
                    Password = "default",
                    UserType = usertype
                };
                HttpResponseMessage response = client.PostAsJsonAsync("api/Staffs/", staff).Result;
                HttpResponseMessage response2 = client.PostAsJsonAsync("api/Members/", User).Result;
                if (response.IsSuccessStatusCode && response2.IsSuccessStatusCode)
                {
                    staffcreateLbl.Text = "";
                    staffcreateLbl.Text += "Staff Created!";
                }
                else
                {
                    RequiredFieldValidator1.IsValid = false;
                    RequiredFieldValidator1.ErrorMessage = "Staff ID has already existed. Please use another ID";
                    staffcreateLbl.Text = "";
                    staffcreateLbl.Text += "Could not create Staff.";// Error code:" + response.StatusCode + ", reason:" + response.ReasonPhrase.ToString() + Environment.NewLine;
                }
            }
        }

        protected void updatestaffBtn_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                HttpClient client = (HttpClient)Session["httpclient"];
                bool approvepermission = false;
                if (approvepermissionRbl.SelectedValue == "Yes")
                {
                    approvepermission = true;
                }
                bool adminright = false;
                if (adminrightRbl.SelectedValue == "Yes")
                {
                    adminright = true;
                }
                var staff = new Staff()
                {
                    StaffID = staffidTbx.Text,
                    Name = staffnameTbx.Text,
                    Email = staffemailTbx.Text,
                    CourseCode = staffcoursecodeRbl.SelectedValue,
                    ApprovePermissions = approvepermission,
                    AdminRights = adminright
                };
                HttpResponseMessage response = client.PutAsJsonAsync("api/Staffs/" + staffDdl.SelectedValue, staff).Result;  // Blocking call!
                if (response.IsSuccessStatusCode)
                {
                    staffupdateLbl.Text = "Staff Updated!";
                }
                else
                {
                    staffupdateLbl.Text = "Error";
                }
            }
        }

        protected void createstudentBtn_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                HttpClient client = (HttpClient)Session["httpclient"];

                var student = new Student()
                {
                    AdminNo = cstudentadminnoTbx.Text,
                    Name = cstudentnameTbx.Text,
                    Email = cstudentemailTbx.Text,
                    CourseCode = cstudentcoursecodeRbl.SelectedValue,
                    CareGroup = cstudentcaregroupTbx.Text,
                    HandphoneNo = cstudenthandphoneTbx.Text,
                    HomeNo = cstudenthomeTbx.Text,
                    Classification = cclassificationRbl.SelectedValue
                };
                var User = new Member()
                {
                    Username = cstudentadminnoTbx.Text,
                    Password = "default",
                    UserType = "Student"
                };
                HttpResponseMessage response = client.PostAsJsonAsync("api/Students/", student).Result;
                HttpResponseMessage response2 = client.PostAsJsonAsync("api/Members/", User).Result;
                if (response.IsSuccessStatusCode && response2.IsSuccessStatusCode)
                {
                    studentcreateLbl.Text = "";
                    studentcreateLbl.Text += "Student Created!";
                }
                else
                {
                    studentcreateLbl.Text = "";
                    RequiredFieldValidator16.IsValid = false;
                    RequiredFieldValidator16.ErrorMessage = "Student already existed.";
                    studentcreateLbl.Text += "Could not create student.";// Error code:" + response.StatusCode + ", reason:" + response.ReasonPhrase.ToString() + Environment.NewLine;
                }
            }
        }

        protected void UpdatestudentBtn_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                HttpClient client = (HttpClient)Session["httpclient"];

                var student = new Student()
                {
                    AdminNo = studentadminnoTbx.Text,
                    Name = studentnameTbx.Text,
                    Email = studentemailTbx.Text,
                    CourseCode = studentcoursecodeRbl.SelectedValue,
                    CareGroup = studentcaregroupTbx.Text,
                    HandphoneNo = studenthandphoneTbx.Text,
                    HomeNo = studenthomeTbx.Text,
                    Classification = classificationRbl.SelectedValue
                };
                HttpResponseMessage response = client.PutAsJsonAsync("api/Students/" + studentDdl.SelectedValue, student).Result;  // Blocking call!
                if (response.IsSuccessStatusCode)
                {
                    studentupdateLbl.Text = "Student Updated";
                }
                else
                {
                    studentupdateLbl.Text = "Error";
                }
            }
        }



        protected void profileBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("adminprofile.aspx");
        }

        protected void managementtoolsBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("adminmanagementtools.aspx");
        }

        protected void faqBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("adminfaq.aspx");
        }

        protected void otherservicesBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("adminotherservice.aspx");
        }

        protected void LogoutBtn_Click(object sender, EventArgs e)
        {
            Session.Abandon();
            FormsAuthentication.SignOut();
            Response.Redirect("default.aspx");
        }




        protected void staffretrieveBtn_Click(object sender, EventArgs e)
        {
            if (staffDdl.SelectedValue != "")
            {
                staffretrieveLbl.Text = "";
                staffretrieveLbl.Text = "Retrieved staff info";
                HttpClient client = (HttpClient)Session["httpclient"];
                HttpResponseMessage response = client.GetAsync("api/Staffs/" + staffDdl.SelectedValue).Result;  // Blocking call!
                if (response.IsSuccessStatusCode)
                {
                    // Parse the response body. Blocking!
                    var staff = response.Content.ReadAsAsync<Staff>().Result;
                    staffidTbx.Text = staff.StaffID;
                    staffnameTbx.Text = staff.Name;
                    staffemailTbx.Text = staff.Email;
                    staffcoursecodeRbl.SelectedValue = staff.CourseCode;
                    if (staff.AdminRights == true)
                    {
                        adminrightRbl.SelectedValue = "Yes";
                    }
                    else
                    {
                        adminrightRbl.SelectedValue = "No";
                    }
                    if (staff.ApprovePermissions == true)
                    {
                        approvepermissionRbl.Text = "Yes";
                    }
                    else
                    {
                        approvepermissionRbl.Text = "No";
                    }
                }
                else
                {
                    staffretrieveLbl.Text = "";
                    staffretrieveLbl.Text = "Nothing Retrieved";
                }
            }
        }

        protected void studentretrieveBtn_Click(object sender, EventArgs e)
        {
            if (studentDdl.SelectedValue != "")
            {
                studentretrieveLbl.Text = "";
                studentretrieveLbl.Text += "Retrieved student info";
                HttpClient client = (HttpClient)Session["httpclient"];
                HttpResponseMessage response = client.GetAsync("api/Students/" + studentDdl.SelectedValue).Result;  // Blocking call!
                if (response.IsSuccessStatusCode)
                {
                    // Parse the response body. Blocking!
                    var student = response.Content.ReadAsAsync<Student>().Result;
                    studentadminnoTbx.Text = student.AdminNo;
                    studentnameTbx.Text = student.Name;
                    studentemailTbx.Text = student.Email;
                    studentcoursecodeRbl.SelectedValue = student.CourseCode;
                    studentcaregroupTbx.Text = student.CareGroup;
                    studenthomeTbx.Text = student.HomeNo;
                    studenthandphoneTbx.Text = student.HandphoneNo;
                    classificationRbl.SelectedValue = student.Classification;
                }
            }
            else
            {
                studentretrieveLbl.Text = "";
                studentretrieveLbl.Text += "Nothing retrieved";
            }
        }
    }
}